package com.xms.schema.api.controller;

import com.xms.core.exception.XmsException;
import com.xms.schema.api.model.EditAttributeModel;
import com.xms.schema.core.AttributeTypeIds;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.OptionSetDetail;
import com.xms.schema.entity.StringMap;
import com.xms.schema.service.attribute.IAttributeFinderService;
import com.xms.schema.service.attribute.IAttributeUpdaterService;
import com.xms.schema.service.optionset.IOptionSetFinderService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.web.framework.model.SetStateModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * AttributeUpdaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/16
 */
@RestController
@RequestMapping("{org}/api/schema/attribute")
public class AttributeUpdaterController extends ApiBaseController {
    private IAttributeUpdaterService _attributeUpdaterService;
    private IAttributeFinderService _attributeFinderService;
    private IOptionSetFinderService _optionSetFinderService;

    @Autowired
    public void AttributeUpdaterController(IAttributeUpdaterService attributeUpdaterService,
                                           IAttributeFinderService attributeFinderService,
                                           IOptionSetFinderService optionSetFinderService) {
        _attributeUpdaterService = attributeUpdaterService;
        _attributeFinderService = attributeFinderService;
        _optionSetFinderService = optionSetFinderService;
    }


    @ApiOperation("修改字段信息")
    @PostMapping("update")
    public JsonResultObject update(@RequestBody EditAttributeModel model) throws XmsException, SQLException {
        Attribute attrInfo = _attributeFinderService.getById(model.AttributeId);
        if (attrInfo == null) {
            return JNotFound();
        }
        attrInfo.setLocalizedname(model.LocalizedName);
        attrInfo.setIsrequired(model.IsRequired);
        attrInfo.setLogenabled(model.LogEnabled);
        attrInfo.setAuthorizationenabled(model.AuthorizationEnabled);
        attrInfo.setDescription(model.Description);
        attrInfo.setValuetype(model.ValueType);
        String attrTypeName = attrInfo.getAttributetypename();

        switch (attrTypeName) {
            case AttributeTypeIds.NVARCHAR:
                attrInfo.setMaxlength(model.MaxLength);
                attrInfo.setDataformat(model.TextFormat);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                }
                break;

            case AttributeTypeIds.NTEXT:
                attrInfo.setDataformat(model.NTextFormat);
                break;

            case AttributeTypeIds.INT:
                attrInfo.setMinvalue((double) model.IntMinValue);
                attrInfo.setMaxvalue((double) model.IntMaxValue);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                } else if (model.ValueType == 3) {
                    attrInfo.setSummaryentityid(model.SummaryEntityId);
                    attrInfo.setSummaryexpression(model.SummaryExpression);
                }
                break;

            case AttributeTypeIds.FLOAT:
                attrInfo.setPrecision(model.FloatPrecision);
                attrInfo.setMinvalue((double) model.FloatMinValue);
                attrInfo.setMaxvalue((double) model.FloatMaxValue);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                } else if (model.ValueType == 3) {
                    attrInfo.setSummaryentityid(model.SummaryEntityId);
                    attrInfo.setSummaryexpression(model.SummaryExpression);
                }
                break;
            case AttributeTypeIds.MONEY:
                attrInfo.setPrecision(model.MoneyPrecision);
                attrInfo.setMinvalue((double) model.MoneyMinValue);
                attrInfo.setMaxvalue((double) model.MoneyMaxValue);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                } else if (model.ValueType == 3) {
                    attrInfo.setSummaryentityid(model.SummaryEntityId);
                    attrInfo.setSummaryexpression(model.SummaryExpression);
                }
                break;

            case AttributeTypeIds.STATUS:
            case AttributeTypeIds.PICKLIST:
                attrInfo.setDisplaystyle(model.OptionSetType);
                attrInfo.setOptionset(_optionSetFinderService.getById(attrInfo.getOptionsetid()));
                if (!attrInfo.getOptionset().getIspublic()) {
                    if (CollectionUtil.isEmpty(model.OptionSetName)) {
                        return JError("字段选项不能为空");
                    }
                    //选项集
                    List<OptionSetDetail> details = new ArrayList<>();
                    int i = 0;
                    for (String item : model.OptionSetName) {
                        if (StringUtil.isEmpty(item)) {
                            continue;
                        }

                        OptionSetDetail osd = new OptionSetDetail();
                        osd.setOptionsetdetailid(UUIDUtil.get());
                        osd.setOptionsetid(attrInfo.getOptionsetid());
                        osd.setName(item);
                        osd.setValue(model.OptionSetValue.get(i));
                        osd.setIsselected(model.IsSelectedOption.get(i));
                        osd.setDisplayorder(i);
                        details.add(osd);

                        i++;
                    }
                    attrInfo.getOptionset().setItems(details);
                }
                break;

            case AttributeTypeIds.STATE:
            case AttributeTypeIds.BIT:
                //新建选项集
                List<StringMap> pickListItems = new ArrayList<>();
                int j = 0;
                for (String item : model.BitOptionName) {
                    StringMap s = new StringMap();
                    s.setStringmapid(UUIDUtil.get());
                    s.setName(item);
                    s.setValue(j == 0 ? 1 : 0);//第一项为true选项
                    s.setDisplayorder(j);
                    s.setAttributeid(attrInfo.getAttributeid());
                    s.setEntityname(attrInfo.getEntityname());
                    s.setAttributename(attrInfo.getName());
                    j++;
                    pickListItems.add(s);
                }
                attrInfo.setPicklists(pickListItems);
                break;

            case AttributeTypeIds.DATETIME:
                attrInfo.setDataformat(model.DateTimeFormat);
                break;

            case AttributeTypeIds.LOOKUP:
                attrInfo.setDisplaystyle(model.LookupType);
                break;

            case AttributeTypeIds.PARTYLIST:
                attrInfo.setDataformat(model.PartyListFormat);
                break;
        }

        _attributeUpdaterService.update(attrInfo);
        return JUpdateSuccess();
    }

    @ApiOperation("设置字段必填状态")
    @PostMapping("setrequiredstate")
    public JsonResultObject setRequiredState(@RequestBody SetStateModel model) {
        if (CollectionUtil.isEmpty(model.recordid)) {
            return JNotSpecifiedParams("recordid");
        }
        return _attributeUpdaterService.updateRequired(model.state, Arrays.asList(model.recordid)) ? JUpdateSuccess() : JUpdateFailure();
    }

    @ApiOperation("设置字段日志状态")
    @PostMapping("setlogstate")
    public JsonResultObject setLoggingState(@RequestBody SetStateModel model) {
        if (CollectionUtil.isEmpty(model.recordid)) {
            return JNotSpecifiedParams("recordid");
        }
        return _attributeUpdaterService.updateLogEnabled(model.state, Arrays.asList(model.recordid)) ? JUpdateSuccess() : JUpdateFailure();
    }
}
